package ca.uwo.android.directoryservice;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.net.Uri;
import android.text.util.Linkify.MatchFilter;
import android.text.util.Linkify.TransformFilter;
import android.util.Log;

public class PhoneUtil {
	public static final TransformFilter PHONETRANSFORM = new TransformFilter() {
		
		
		public final String transformUrl(final Matcher match, String url) {
//			Log.i("PhoneUtil", "in transform filter");
			StringBuilder buffer = new StringBuilder();
			String matchingRegion = match.group();
			for (int i = 0, size = matchingRegion.length(); i < size; i++) {
				char character = matchingRegion.charAt(i);

				// This may work for later version
				if (character == 'x' || character == 'X') {
					buffer.append(",");
					buffer.append(",");
					buffer.append(",");
				}

				if (character == '+' || Character.isDigit(character)) {
					buffer.append(character);
				}
			}
//			Log.i("PhoneUtil", "about to return encoded uri:  " + buffer.toString());
			return Uri.encode(buffer.toString());
		}
	};
	
	public static final MatchFilter PHONEMATCH = new MatchFilter() {

		@Override
		public boolean acceptMatch(CharSequence s, int start, int end) {
			
			int digitCount = 0;
			if(s.charAt(0) == 'x' || s.charAt(0) == 'X')
				return false;
				
			for (int i = start; i < end; i++) {
                if (Character.isDigit(s.charAt(i))) {
                    digitCount++;
                    if (digitCount >= 5) {
                        return true;
                    }
                }
            }
			return false;
		}
		
	};

	public static final String CALLURI = "tel:";

	public static final Pattern PHONE = Pattern.compile("(\\+[0-9]+[\\- \\.]*)?"
			+ "(\\([0-9]+\\)[\\- \\.]*)?"
			+ "([0-9][0-9\\- \\.][0-9\\- \\.]+[0-9])"
			+ "([\\s]*[xX]+[0-9]+)?"); 

//	public static final Pattern PHONE = Pattern.compile("((\\+[0-9]+[\\- \\.]*)? + "
//														+ "(\\([0-9]+\\)[\\- \\.]*)? + "
//														+ "([0-9][0-9\\- \\.][0-9\\- \\.]+[0-9]))"
//														+ "((\\s*)? + [[x][X]]* + ([0-9]*))?"); 
}
